package com.corecloud.controller.sys;

import java.security.Principal;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.corecloud.entity.SysAreaEntity;
import com.corecloud.entity.SysDeptEntity;
import com.corecloud.entity.SysUserEntity;
import com.corecloud.entity.SysUserRoleEntity;
import com.corecloud.service.SysAreaService;
import com.corecloud.service.SysDeptService;
import com.corecloud.service.SysRoleService;
import com.corecloud.service.SysUserRoleService;
import com.corecloud.service.SysUserService;
import com.corecloud.tools.AjaxResultData;
import com.corecloud.tools.MD5Utils;
import com.corecloud.tools.PageDemo;

/**
 * 用户管理相关
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysAreaService sysAreaService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private SysRoleService sysRoleService;

	/**
	 * 用户信息首页
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(Principal principal){
		ModelAndView modelAndView = new ModelAndView("user/index");
		return modelAndView;
	}

	/**
	 * 用户信息详情页
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/detail")
	public ModelAndView detail(Principal principal,Integer id){
		ModelAndView modelAndView = new ModelAndView("user/detail");
		if(!StringUtils.isEmpty(id)){
			SysUserEntity userInfo = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("id",id));
			modelAndView.addObject("userInfo",userInfo);
			if(!StringUtils.isEmpty(userInfo.getDeptId())){
				modelAndView.addObject("deptInfo",sysDeptService.selectOne(new QueryWrapper<SysDeptEntity>().eq("id",userInfo.getDeptId())));
			}
			if(!StringUtils.isEmpty(userInfo.getAreaId())){
				modelAndView.addObject("areaInfo",sysAreaService.selectOne(new QueryWrapper<SysAreaEntity>().eq("area_id", userInfo.getAreaId())));
			}
		}
		return modelAndView;
	}

	/**
	 * 添加用户页
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(Principal principal){
		ModelAndView modelAndView = new ModelAndView("user/add");
		modelAndView.addObject("areaList",sysAreaService.selectList(new QueryWrapper<SysAreaEntity>()));
		modelAndView.addObject("deptList",sysDeptService.selectList(new QueryWrapper<SysDeptEntity>().eq("is_valid",1)));
		return modelAndView;
	}

	/**
	 * 角色列表页数据（分页）
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Page<SysUserEntity> list(Principal principal, SysUserEntity info, PageDemo pageDemo){
		QueryWrapper<SysUserEntity> qw = new QueryWrapper();
		//拼装查询条件
		if(!StringUtils.isEmpty(info.getIsValid())){ qw.eq("is_valid",info.getIsValid()); }
		if(!StringUtils.isEmpty(info.getUserName())){ qw.like("user_name",info.getUserName()); }
		if(!StringUtils.isEmpty(info.getNickName())){ qw.like("nick_name",info.getNickName()); }
		OrderItem oi = new OrderItem();
		oi.setAsc(false);
		oi.setColumn("id");
		pageDemo.addOrder(oi);
		List<SysUserRoleEntity> listByParas = sysUserRoleService.getListByParas(new QueryWrapper<SysUserRoleEntity>());
		Page<SysUserEntity> infoByPage = sysUserService.getInfoByPage(pageDemo, qw);
		for (int i = 0; i < infoByPage.getRecords().size(); i++) {
			Integer id = infoByPage.getRecords().get(i).getId();
			for (int j = 0; j < listByParas.size(); j++) {
				Integer userId = listByParas.get(j).getUserId();
				if (id.equals(userId)){
					String roleName = listByParas.get(j).getRoleName();
					infoByPage.getRecords().get(i).setRoleName(roleName);
				}
			}
		}
		return infoByPage;
	}


	/**
	 * 保存用户信息
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public AjaxResultData save(Principal principal, SysUserEntity info,String birthdayStr){
		if(StringUtils.isEmpty(info.getUserName())){ return new AjaxResultData(500,"请输入用户名"); }
		if(StringUtils.isEmpty(info.getNickName())){ return new AjaxResultData(500,"请输入系统昵称"); }
		if(StringUtils.isEmpty(info.getName())){ return new AjaxResultData(500,"请输入真实姓名"); }
		if(StringUtils.isEmpty(info.getName())){ return new AjaxResultData(500,"请选择所属地市"); }
		if(StringUtils.isEmpty(info.getName())){ return new AjaxResultData(500,"请选择所属机构"); }

		SysUserEntity userInfo = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",info.getUserName()));

		if(userInfo != null && !StringUtils.isEmpty(userInfo.getUserName())){ return new AjaxResultData(500,"用户名已被占用"); }

		//配置默认数据
		try {
			//字符串转换为小写
			info.setUserName(info.getUserName().trim().toLowerCase());
			String password= info.getPassword()==null || info.getPassword().trim().equals("")?"hnzy1234":info.getPassword().trim();
	        String salt = "{1#2$3%4(5)6@7!poeeww$3%4(5)djjkkldss}";
			info.setPassword(MD5Utils.encodeByMD5(password,salt));
			info.setSource(info.getSource()==null?0:info.getSource());
			info.setCreateTime(new Date());
			info.setGender(3);
			sysUserService.insertInfo(info);

			SysUserEntity userInfoID = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name",info.getUserName()));

			if (userInfoID.getId() == null){ return new AjaxResultData(500,"权限插入失败，请在手动赋予权限"); }

			return new AjaxResultData( userInfoID.getId(), "操作成功");
		}catch (Exception e){
			e.printStackTrace();
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}

	/**
	 * 保存外部系统进来的用户信息(其他系统调用该接口，同步创建用户信息)
	 * @return
	 */
	@PostMapping("/saveExternalUser")
	@ResponseBody
	public AjaxResultData saveExternalUser(Principal principal, SysUserEntity info,String birthdayStr){
		//TODO 校验外部系统
		info.setSource(2);
		return save( principal,  info, birthdayStr);
	}

	/**
	 * 修改用户页
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(Principal principal,Integer id){
		ModelAndView modelAndView = new ModelAndView("user/edit");
		modelAndView.addObject("userInfo",sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("id",id)));
		modelAndView.addObject("areaList",sysAreaService.selectList(new QueryWrapper<SysAreaEntity>()));
		modelAndView.addObject("deptList",sysDeptService.selectList(new QueryWrapper<SysDeptEntity>().eq("is_valid",1)));
		return modelAndView;
	}

	/**
	 * 保存外部系统进来的用户密码(其他系统调用该接口，同步创建用户密码)
	 * @return
	 */
	@PostMapping("/updateExternalUserPwd")
	@ResponseBody
	public AjaxResultData updateExternalUserPwd(String account, String pwd, SysUserEntity info){
		SysUserEntity sysUserEntity = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("user_name", account));
		if (sysUserEntity!=null){
            sysUserEntity.setPassword(pwd);
			sysUserService.updateInfo(sysUserEntity);
		}else {
			// 新建用户
			return saveExternalUser( null,  info, null);
		}
		return new AjaxResultData( 200, "操作成功");
	}

	/**
	 * 保存用户信息
	 * @return
	 */
	@RequestMapping("/update")
	@ResponseBody
	public AjaxResultData update(Principal principal, SysUserEntity info){
		if(StringUtils.isEmpty(info.getNickName())){ return new AjaxResultData(500,"请输入系统昵称"); }
		if(StringUtils.isEmpty(info.getName())){ return new AjaxResultData(500,"请输入真实姓名"); }
		if(StringUtils.isEmpty(info.getAreaId())){ return new AjaxResultData(500,"请选择所属地市"); }
		if(StringUtils.isEmpty(info.getDeptId())){ return new AjaxResultData(500,"请选择所属机构"); }

		try {
			SysUserEntity oldInfo = sysUserService.selectOne(new QueryWrapper<SysUserEntity>().eq("id",info.getId()));
			if(!StringUtils.isEmpty(info.getPassword()) && !info.getPassword().equals("默认密码：hnzy1234")){
				String salt = "{1#2$3%4(5)6@7!poeeww$3%4(5)djjkkldss}";
				oldInfo.setPassword(MD5Utils.encodeByMD5(info.getPassword(),salt));
			}
			oldInfo.setNickName(info.getNickName());//昵称
			oldInfo.setName(info.getName());//真实姓名
			oldInfo.setIsValid(info.getIsValid());//是否启用
			oldInfo.setAreaId(info.getAreaId());//地域信息ID
			oldInfo.setDeptId(info.getDeptId());//机构信息ID
			if(!StringUtils.isEmpty(info)){ oldInfo.setPhone(info.getPhone()); }//电话
			if(!StringUtils.isEmpty(info)){ oldInfo.setAddress(info.getAddress()); }//详细地址
			if(!StringUtils.isEmpty(info)){ oldInfo.setUserType(info.getUserType()); }//用户类型
			sysUserService.updateInfo(oldInfo);
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}


	/**
	 * 删除用户信息
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public AjaxResultData delete(Principal principal, Integer id){
		if(StringUtils.isEmpty(id)){
			return new AjaxResultData(500,"参数异常,请联系管理员");
		}
		try {
			sysUserService.deleteInfo(id);
			//同步清除用户角色关联信息
			sysUserRoleService.deleteByParas(new QueryWrapper<SysUserRoleEntity>().eq("user_id",id));
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}





}
